/********************************************************/
/*	Author:		gong_libin			*/
/*	Date:		2017_11_01			*/
/*	File:		CmEvent.cpp			*/
/********************************************************/

#include "CmEvent.h"

CmNet::CCmTcp CCmEvent::m_CTcp;

void* CCmEvent::CmEventDispatch()
{
	return CM_SUCCESS == event_base_dispatch(m_pstBase) ? m_pstBase : NULL;
}

void CCmEvent::CmEventCall(void(*pFun)(struct evhttp_request*, void*), void* pPara)
{
	struct evhttp* pstHttp = evhttp_new(m_pstBase);

	evhttp_accept_socket(pstHttp, m_CTcp.CmNetGetSocket());
	evhttp_set_timeout(pstHttp, CM_EVT_TMOUT);
	evhttp_set_gencb(pstHttp, pFun, pPara);

	return;
}

CMMAP_C* CCmEvent::CmEventKvsGet(struct evhttp_uri* pstUri)
{
	CMSTR_C CVal;
	CMMAP_C* pCKvs = NULL;
	struct evkeyvalq stKvs;
	const char* pszUri = evhttp_uri_get_query(pstUri);

	if (CM_SUCCESS == evhttp_parse_query_str(pszUri, &stKvs)) {
		pCKvs = new CMMAP_C();
		for (struct evkeyval* pstCur = stKvs.tqh_first; NULL != pstCur; pstCur = pstCur->next.tqe_next) {
			pCKvs->CmMapInsert(CMSTR_C(pstCur->key), CVal.assign(pstCur->value));
		}
	}

	return pCKvs;
}

void CCmEvent::CmEventKvsDel(CMMAP_C* pCKvs)
{
	pCKvs->CmMapClear();
	free(pCKvs);

	return;
}

CMADXPARA_S* CCmEvent::CmEventContent(struct evbuffer* pstBuf)
{
	CMADXPARA_S* pstPara = NULL;
	int iSize = EVBUFFER_LENGTH(pstBuf);

	if (0 < iSize && iSize < CM_KBYTES8) {
		if (NULL != (pstPara = CmEventParaMalloc())) {
			memcpy(pstPara->m_stSspReq.m_uszMsg, EVBUFFER_DATA(pstBuf), iSize);
			pstPara->m_stSspReq.m_uiMsg = iSize;
		}
	}

	return pstPara;
}

void CCmEvent::CmEventAddHeader(struct evkeyvalq* pstInput, char* pszKey, char* pszVal)
{
	evhttp_add_header(pstInput, pszKey, pszVal);

	return;
}

const char* CCmEvent::CmEventFindHeader(struct evkeyvalq* pstInput, const char* pszKey)
{
	return evhttp_find_header(pstInput, pszKey);
}

void CCmEvent::CmEventSendReply(struct evhttp_request* pstReq, UCHAR* puszData, int iSize)
{
	struct evbuffer* pstBuf = evbuffer_new();

	CM_EVT_ADDBUFFER(pstBuf, puszData, iSize);
	evhttp_send_reply(pstReq, HTTP_OK, "OK", pstBuf);
	evbuffer_free(pstBuf);

	return;
}

void CCmEvent::CmEventPthread()
{
	evthread_use_pthreads();

	return;
}

int CCmEvent::CmEventInit(char* pszPort)
{
	if (CM_SUCCESS == CCmEvent::m_CTcp.CmTcpInit(pszPort)) {
		CCmEvent::m_CTcp.CmNetSetNonBlock();
	}
	else {
		return CM_FAILURE;
	}

	return CM_SUCCESS;
}

CMADXPARA_S* CCmEvent::CmEventParaMalloc()
{
	return (CMADXPARA_S*)CmMalloc(sizeof(CMADXPARA_S));
}

void CCmEvent::CmEventParaFree(CMADXPARA_S* pstPara)
{
	if (NULL != pstPara) {
		CmFree((void**)&pstPara);
	}

	return;
}
